package com.xfcycle.zebrabikegp.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;
import com.xfcycle.zebrabikegp.listener.CleanAppCacheListener;
import com.xfcycle.zebrabikegp.listener.SharePreferencesDeleteDataListener;
import com.xfcycle.zebrabikegp.util.AppInfoUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;

import java.util.HashMap;
import java.util.Map;

public class SettingActivity extends RootActivity {

    private static final String TAG = "SettingActivity";

    private ImageView iv_setting_back;

    private RelativeLayout rl_setting_clean_cache;
    private RelativeLayout rl_setting_bike_setting;
    private RelativeLayout rl_setting_bike_info;
    private RelativeLayout rl_setting_bike_test;
    private RelativeLayout rl_setting_log_out;

    private TextView tv_setting_app_cache_content;

    private AlertDialog cleanCacheDialog;
    private AppInfoUtil appInfoUtil;

    private HandleDataBySharePreferencesUtil handleDataBySharePreferencesUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        initView();
        initViewListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setViewContent();
    }

    private void initView() {
        iv_setting_back = (ImageView) findViewById(R.id.iv_setting_back);

        rl_setting_clean_cache = (RelativeLayout) findViewById(R.id.rl_setting_clean_cache);
        rl_setting_bike_setting = (RelativeLayout) findViewById(R.id.rl_setting_bike_setting);
        rl_setting_bike_info = (RelativeLayout) findViewById(R.id.rl_setting_bike_info);
        rl_setting_bike_test = (RelativeLayout) findViewById(R.id.rl_setting_bike_test);
        rl_setting_log_out = (RelativeLayout) findViewById(R.id.rl_setting_log_out);

        tv_setting_app_cache_content = (TextView) findViewById(R.id.tv_setting_app_cache_content);

        handleDataBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(this);
        appInfoUtil = new AppInfoUtil(this);

        //定义清理内存弹出框
        createCleanCacheDialog();
    }

    private void initViewListener() {
        //回退事件监听
        iv_setting_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //清除app缓存
        rl_setting_clean_cache.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != cleanCacheDialog && !cleanCacheDialog.isShowing()) {
                    cleanCacheDialog.show();
                }
            }
        });

        //跳转到自行车设置页面
        rl_setting_bike_setting.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                activityChange(BIKE_SETTING_ACTIVITY, null, null);
            }
        });

        //跳转到车辆信息界面
        rl_setting_bike_info.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                activityChange(BIKE_FRAME_INFO, null, null);
            }
        });

        //跳转到车辆检测界面
        rl_setting_bike_test.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                activityChange(BIKE_TEST_ACTIVITY, null, null);
            }
        });

        //退出登陆
        rl_setting_log_out.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String uid = handleDataBySharePreferencesUtil.getDateFromSharePre(APP_INFO_SP_NAME, "uid");

                //移除蓝牙连接
                HandleDataByBLEUtil.deleteInstance();

                //告诉服务器端退出登陆
                if (null != uid && !"".equals(uid)) {
                    Map<String, String> params = new HashMap<>();
                    params.put(WebConstant.LOGOUT_PATH_USER_ID, uid);
                    new GetJsonFromWebJob(WebConstant.LOGOUT_PATH, WebConstant.GET, params, REQUEST_SIGN_LOGOUT, SettingActivity.this).start();
                }
            }
        });

        //清除sp所有内容监听
        handleDataBySharePreferencesUtil.onDeleteDataInSharePreListener(new SharePreferencesDeleteDataListener() {
            @Override
            public void sharePreferencesDeleteDataFinish() {
                //跳转到登录页面
                activityChange(LOGIN_ACTIVITY, null, null);
            }
        });

        //清除缓存数据监听
        appInfoUtil.setOnCleanAppCacheListener(new CleanAppCacheListener() {
            @Override
            public void cleanAppCacheFinish() {
                tv_setting_app_cache_content.setText(appInfoUtil.getAppCacheSize());
            }
        });
    }

    private void setViewContent() {

        //展示当前app缓存数据大小
        tv_setting_app_cache_content.setText(appInfoUtil.getAppCacheSize());
    }

    /**
     * 处理从网络获得的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        Log.e(TAG, "dealDataFromWeb: -----------" + webResult);

        //判断账号登出成功
        if (REQUEST_SIGN_LOGOUT == webSign && "".equals(webResult)) {

            //清除sp中所有数据
            handleDataBySharePreferencesUtil.deleteAllDataInSharePre(APP_INFO_SP_NAME);
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            }catch (Exception e){
                Toast.makeText(this.getApplicationContext(), ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }
            return;
        }
    }

    /**
     * 创建清理内存弹出框
     */
    private void createCleanCacheDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        // 标题
        builder.setTitle("Clean cache");
        // 内容
        builder.setMessage("Are you sure clean the app cache？");

        // 确定（积极）
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                appInfoUtil.cleanCache();
            }
        });

        // 取消（消极）
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (null != cleanCacheDialog && cleanCacheDialog.isShowing()) {
                    cleanCacheDialog.dismiss();
                }
            }
        });

        //创建dialog
        cleanCacheDialog = builder.create();
    }
}
